package com.eden.manage.service;

import com.eden.manage.dto.UserInfoDto;
import com.eden.manage.dto.common.UserTypeDto;
import com.eden.manage.mapper.EdenPlatAgentInfoMapper;
import com.eden.manage.mapper.EdenPlatMapper;
import com.eden.manage.model.EdenPlat;
import com.eden.manage.model.EdenPlatAgentInfo;
import com.eden.manage.utils.WebUserUtils;
import eden.api.common.enums.UserTypeEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class CommonService {

    private final EdenPlatMapper edenPlatMapper;

    private final EdenPlatAgentInfoMapper platAgentInfoMapper;

    public List<UserTypeDto> getUserType(){
        UserInfoDto userInfo = WebUserUtils.getUserInfo();
        List<UserTypeDto> list = new ArrayList<>();
        if(UserTypeEnum.ADMIN.getCode().equals(userInfo.getType())){
            // 管理员新增管理员和平台商信息
            UserTypeDto userTypeDto = new UserTypeDto();
            userTypeDto.setId(UserTypeEnum.ADMIN.name()+"0");
            userTypeDto.setName("管理员");
            list.add(userTypeDto);
            List<EdenPlat> edenPlats = Optional.ofNullable(edenPlatMapper.selectAvailablePlat()).orElse(new ArrayList<>(0));
            for (EdenPlat edenPlat : edenPlats) {
                UserTypeDto dto = new UserTypeDto();
                dto.setId(UserTypeEnum.PLAT.name()+edenPlat.getId());
                dto.setName(edenPlat.getPlatName());
                list.add(dto);
            }
        }else if(UserTypeEnum.PLAT.getCode().equals(userInfo.getType())){
            // 平台可以查询下级的一级代理商
            List<EdenPlatAgentInfo> agentInfos = Optional.ofNullable(platAgentInfoMapper.selectListFirstLevel(userInfo.getPlatId())).orElse(new ArrayList<>(0));
            for (EdenPlatAgentInfo agentInfo : agentInfos) {
                UserTypeDto dto = new UserTypeDto();
                dto.setId(UserTypeEnum.AGENT.name()+agentInfo.getId());
                dto.setName(agentInfo.getAgentName());
                list.add(dto);
            }
        }else if(UserTypeEnum.AGENT.getCode().equals(userInfo.getType())){
            // 平台可以查询下级的一级代理商
            List<EdenPlatAgentInfo> agentInfos = Optional.ofNullable(platAgentInfoMapper.selectListByNextLevel(userInfo.getPlatId(), userInfo.getAgentId())).orElse(new ArrayList<>(0));
            for (EdenPlatAgentInfo agentInfo : agentInfos) {
                UserTypeDto dto = new UserTypeDto();
                dto.setId(UserTypeEnum.AGENT.name()+agentInfo.getId());
                dto.setName(agentInfo.getAgentName());
                list.add(dto);
            }
        }
        return list;
    }

}
